package cn.gailvlun.gll.presentation.xroom

import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.RadioButton
import cn.gailvlun.gll.R
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.cross.*
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.xroom.vm.CrossRoomGameInfoViewModel
import cn.gailvlun.gll.util.*
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxRadioGroup
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.rxkotlin.Observables
import kotlinx.android.synthetic.main.activity_cross_room_game_info.*

class CrossRoomGameInfoActivity : BaseActivity() {
    companion object {
        fun openActivity(context: Context) {
            val intent = Intent(context, CrossRoomGameInfoActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initComponent() {
        setContentView(R.layout.activity_cross_room_game_info)

        mViewModel = ViewModelProviders.of(this).get(CrossRoomGameInfoViewModel::class.java)

        Glide.with(mContext)
                .load(R.drawable.img_cross_room_introduce)
                .into(object: SimpleTarget<Drawable>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        ll_bg.setBackgroundDrawable(resource)
                    }
                })
    }

    private var lastCheckId: Int? = null
    private var mViewModel: CrossRoomGameInfoViewModel? = null

    private var currentSelectPos: Int? = null

    override fun createHandler() {
        nbv.setOnBackListener {
            onBackPressed()
        }

        val rgOb = RxRadioGroup.checkedChanges(rg_question)
                .skipInitialValue()

        Observables.combineLatest(RxTextView.textChanges(et_first),
                RxTextView.textChanges(et_second),
                RxTextView.textChanges(et_third), rgOb) { c1, c2, c3, checkedId ->
            lastCheckId?.apply {
                rg_question.getChildAt(getCheckedIdPosition(this) * 2 + 1).visibility = View.GONE
            }
            rg_question.getChildAt(getCheckedIdPosition(checkedId) * 2 + 1).visibility = View.VISIBLE
            currentSelectPos = getCheckedIdPosition(checkedId)
            lastCheckId = checkedId

            return@combineLatest currentSelectPos?.run {
                when (this) {
                    0 -> {
                        c1.isNotEmpty()
                    }
                    1 -> {
                        c2.isNotEmpty()
                    }
                    2 -> {
                        c3.isNotEmpty()
                    }
                    else -> false
                }
            } ?: false
        }.subscribe {
            btn_start_match.isEnabled = it
        }

        RxView.clicks(btn_start_match)
                .subscribe {
                    val startMatchReq = StartMatchReq()
                    when (rg_match.checkedRadioButtonId) {
                        R.id.rb_any -> startMatchReq.target_gender = TargetGender.U
                        R.id.rb_male -> startMatchReq.target_gender = TargetGender.M
                        R.id.rb_female -> startMatchReq.target_gender = TargetGender.F
                    }
                    startMatchReq.question_id = rg_question.getChildAt(getCheckedIdPosition(rg_question.checkedRadioButtonId) * 2).tag as Int
                    startMatchReq.answer = (rg_question.getChildAt(getCheckedIdPosition(rg_question.checkedRadioButtonId) * 2 + 1) as EditText).text.toString()

                    if (startMatchReq.answer.isBlank()) {
                        ToastUtil.showShort("不许走，你还没回答呢")
                        return@subscribe
                    }

                    val pd = DialogUtil.showIndeterminate(mContext)
                    HttpMethods.getCrossService()
                            .startMatch(startMatchReq)
                            .compose(RxUtil.applyScheduler())
                            .compose(bindToLifecycle())
                            .subscribe(object : HttpSubscriber<StartMatchRes>() {
                                override fun onSuccess(response: StartMatchRes?) {
                                    run {
                                        when (rg_match.checkedRadioButtonId) {
                                            R.id.rb_male -> MatchPreference.MALE
                                            R.id.rb_female -> MatchPreference.FEMALE
                                            else -> null
                                        }
                                    }.apply {
                                        SPUtil.put(SPUtil.USER, "xRoomMatchIntent", this)
                                    }

                                    mViewModel?.startMatchRes = response

                                    val trans = supportFragmentManager.beginTransaction()
                                    trans.add(R.id.match_container, CrossRoomMatchFragment())
                                    trans.commit()
                                }

                                override fun onFailure(errMsg: String?, response: StartMatchRes?, code: Int) {
                                    DialogUtil.showError(mContext, errMsg)
                                }

                                override fun onFinish() {
                                    super.onFinish()

                                    pd.dismiss()
                                }
                            })
                }

        btn_change.setOnClickListener {
            loadQuestions()
        }
    }

    private fun getCheckedIdPosition(checkedId: Int): Int {
        return when (checkedId) {
            R.id.rb_first -> 0
            R.id.rb_second -> 1
            R.id.rb_third -> 2
            else -> -1
        }
    }

    override fun loadData(savedInstanceState: Bundle?) {
        val matchPreference = SPUtil.get(SPUtil.USER, "xRoomMatchIntent", MatchPreference::class.java)

        when (matchPreference) {
            null -> {
                rg_match.check(R.id.rb_any)
            }
            MatchPreference.FEMALE -> {
                rg_match.check(R.id.rb_female)
            }
            MatchPreference.MALE -> {
                rg_match.check(R.id.rb_male)
            }
        }

        loadQuestions()
    }

    private fun clearAllEditText() {
        for (i in 0 until rg_question.childCount) {
            if (rg_question.getChildAt(i) !is EditText) {
                continue
            }
            (rg_question.getChildAt(i) as EditText).text = null
        }
    }

    private fun loadQuestions() {
        clearAllEditText()

        
        val pd = DialogUtil.showIndeterminate(mContext)
        HttpMethods.getCrossService()
                .questionList
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListRes<CrossQuestion>>() {
                    override fun onSuccess(response: ListRes<CrossQuestion>) {
                        pd.dismiss()
                        for ((index, value) in response.results.withIndex()) {
                            (rg_question.getChildAt(index * 2) as RadioButton).text = value.content
                            rg_question.getChildAt(index * 2).tag = value.id
                        }
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<CrossQuestion>?, code: Int) {
                        pd.dismiss()
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }
}